package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.jgspatrol.utils.MyConstant.MAP_INDEX;
import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;

import androidx.recyclerview.widget.GridLayoutManager;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.activity.NaviMapActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.SPTools;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.FireNoticePictureAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.FireNoticeDetailsBean;
import com.mingtu.jgspatrol.databinding.ActivityIndexFireDetails1Binding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class IndexFireDetails1Activity extends MyBaseActivity<ActivityIndexFireDetails1Binding> {
    private AMap aMap;
    private List<Marker> markers = new ArrayList<>();
    private String fireId;
    private NaviLatLng startPoint;
    private LatLng location;
    private LatLng firLocation;
    private FireNoticePictureAdapter firePictureVideoAdapter;
    private List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> DataBean = new ArrayList<>();
    private ArrayList<LocalMedia> selectPictureList = new ArrayList<>();
    private String createTime;
    private String lngStr;
    private String latStr;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_index_fire_details1;
    }

    @Override
    protected void initView() {
        setModuleTitle("待确认火情");
    }

    @Override
    protected void initData() {
        GridLayoutManager layoutManager1 = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        binding.recyclerPicture.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(15), false));
        binding.recyclerPicture.setLayoutManager(layoutManager1);

        firePictureVideoAdapter = new FireNoticePictureAdapter(context, DataBean);
        binding.recyclerPicture.setAdapter(firePictureVideoAdapter);
        firePictureVideoAdapter.setOnItemClickListener(new FireNoticePictureAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList);
            }
        });

        addClickListener(this, binding.ivFireLocation, binding.but1, binding.but2);

    }

    @Override
    protected void getData() {
        fireId = getIntent().getStringExtra("fireId");
        getFireNoticetDetails();
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                String address = SPStaticUtils.getString(SPTools.address);
                String longitude = SPStaticUtils.getString(SPTools.lng);
                String latitude = SPStaticUtils.getString(SPTools.lat);

                //火情点
                String lng = getIntent().getStringExtra("lng");
                String lat = getIntent().getStringExtra("lat");

                List<LatLng> latLngs = new ArrayList<>();

                if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
                    location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                    startPoint = new NaviLatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                    //添加Marker
                    MarkerOptions markerOptions = new MarkerOptions()
                            .position(location)
                            .zIndex(MAP_INDEX)
                            .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
                    Marker marker = aMap.addMarker(markerOptions);
                    markers.add(marker);
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                }
                binding.tvAddress.setText(address);

                if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
                    double fireLng = Double.parseDouble(lng);
                    double fireLat = Double.parseDouble(lat);
                    firLocation = new LatLng(fireLat, fireLng);
                    NaviLatLng endPoint = new NaviLatLng(fireLat, fireLng);
                    ApplicationInfo appInfo = getApplicationInfo();
                    ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                    for (int i = 1; i <= 74; i++) {
                        int resID = getResources().getIdentifier("icon_fire" + i, "mipmap", appInfo.packageName);
                        giflist.add(BitmapDescriptorFactory.fromResource(resID));
                    }

                    MarkerOptions markerOptions = new MarkerOptions()
                            .position(firLocation)
                            .period(3)
                            .icons(giflist);
                    Marker marker = aMap.addMarker(markerOptions);
                    markers.add(marker);
                }

                latLngs.add(location);
                latLngs.add(firLocation);
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), 200));
            }
        });
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_map1:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case R.id.rb_map2:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
                        break;
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁地图对象
        try {

            for (Marker marker : markers) {
                marker.remove();
            }
            if (binding.mapView != null) {
                binding.mapView.onDestroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.but1:
                bundle.putString("fireId", fireId);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), IndexFireSureActivity.class, bundle);
                break;
            case R.id.but2:
                bundle.putString("fireId", fireId);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), IndexFireSendActivity.class, bundle);
                break;
            case R.id.iv_fire_location:

                bundle.putString("lng", lngStr);
                bundle.putString("lat", latStr);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), NaviMapActivity.class, bundle);
                break;
        }
    }

    /**
     * 火情详情
     */
    private void getFireNoticetDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("fireId", fireId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FIRE_NOTICE_DETAILS + "/" + fireId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                FireNoticeDetailsBean fireNoticeDetailsBean = new FireNoticeDetailsBean();
                                fireNoticeDetailsBean = gson.fromJson(result, FireNoticeDetailsBean.class);
                                FireNoticeDetailsBean.DataBean dataBean = fireNoticeDetailsBean.getData();
                                if (dataBean != null) {
                                    createTime = dataBean.getCreateTime();
                                    String uploadType = dataBean.getUploadType();
                                    String fireAddress = dataBean.getAddress();
                                    String lnglat = dataBean.getLnglat();
                                    List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> entityListBeans = dataBean.getFireInfoAttachEntityList();
                                    DataBean.addAll(entityListBeans);

                                    if (!StringUtils.isEmpty(createTime)) {
                                        binding.tvTime.setText(createTime);
                                    }
                                    if (!StringUtils.isEmpty(uploadType)) {
                                        binding.tvType.setText(uploadType);
                                    }

                                    if (!StringUtils.isEmpty(fireAddress)) {
                                        binding.tvFireAddress.setText(fireAddress);
                                    }
                                    if (!StringUtils.isEmpty(lnglat)) {
                                        if (lnglat.indexOf(",") != -1) {
                                            String[] lnglatArray = lnglat.split(",");
                                            lngStr = lnglatArray[0];
                                            latStr = lnglatArray[1];
                                            double lat = Double.parseDouble(latStr);
                                            double lng = Double.parseDouble(lngStr);
                                            String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                                            String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);
                                            binding.tvFireLocation.setText(myLng + "," + myLat);
                                        }
                                    }

                                    binding.layoutPicture.setVisibility(View.GONE);
                                    if (DataBean != null) {
                                        if (DataBean.size() > 0) {
                                            binding.layoutPicture.setVisibility(View.VISIBLE);
                                        }
                                    }

                                    for (int i = 0; i < DataBean.size(); i++) {
                                        String url = DataBean.get(i).getUrl();

                                        LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
                                        localMedia.setPosition(i);
                                        selectPictureList.add(localMedia);
                                    }

                                    firePictureVideoAdapter.upData(DataBean);

                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }

}